package com.linx.commonlib

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment

fun Activity.isNavigationBarExist(): Boolean {
    val navId = "navigationBarBackground"
    val vp = window.decorView as ViewGroup
    vp.children.forEach {
        try {
            if (it.id != 0xFFFFFFFF.toInt() && resources.getResourceEntryName(it.id) == navId) {
                return true
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    return false
}

fun Context.toast(msg: String, isLong: Boolean = false) {
    Toast.makeText(this, msg, if (isLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT).show()
}

fun setVisible(visible: Boolean, vararg views: View) {
    views.forEach {
        it.isVisible = visible
    }
}

fun View.showSoftInput() {
    val inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputManager.showSoftInput(this, 0)
}

fun View.hideSoftInput() {
    val inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputManager.hideSoftInputFromWindow(windowToken, 0)
}

fun Activity.hideSoftInput() {
    window.decorView.hideSoftInput()
}

inline fun <reified T : Context> Context.start(vararg params: Pair<String, Any?>) {
    val intent = Intent(this, T::class.java)
    if (params.isNotEmpty()) {
        val bundle = bundleOf(*params)
        intent.putExtras(bundle)
    }
    startActivity(intent)
}

inline fun <reified T : Context> Activity.startForResult(requestCode: Int, vararg params: Pair<String, Any?>) {
    val intent = Intent(this, T::class.java)
    if (params.isNotEmpty()) {
        val bundle = bundleOf(*params)
        intent.putExtras(bundle)
    }
    startActivityForResult(intent, requestCode)
}

inline fun <reified T : Context> Fragment.startForResult(requestCode: Int, vararg params: Pair<String, Any?>) {
    val intent = Intent(context, T::class.java)
    if (params.isNotEmpty()) {
        val bundle = bundleOf(*params)
        intent.putExtras(bundle)
    }
    startActivityForResult(intent, requestCode)
}